package com.wugh.fast.security.core.web;

import com.alibaba.fastjson.JSON;
import com.wugh.fast.kernel.core.enums.FastExceptionEnum;
import com.wugh.fast.kernel.core.exception.FastBusinessException;
import com.wugh.fast.kernel.util.HttpUtils;
import com.wugh.fast.module.api.vo.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 说明: 用户授权失败处理
 *
 * @author wugh
 * @date 2018-09-18 14:29
 */
@Slf4j
public class JsonAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.info("系统-用户中心-登录失败,用户[{}]", request.getParameter("username"));
        if (HttpUtils.isAjaxRequest(request)) {
            ResponseVO<Void> error = ResponseVO.fail(new FastBusinessException("验证失败", FastExceptionEnum.GLOBAL_BUSINESS_EXCEPTION));
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(error));
        } else {
            super.onAuthenticationFailure(request, response, exception);
        }
    }
}
